from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.hashers import make_password, check_password
from .models import y_yamllist, y_yamlhosts, y_yamlkeys, y_yamlgroup, r_group_rules, y_history
from datetime import datetime
from django.http import HttpResponse, HttpResponseRedirect
from django.db import connection, transaction
from .tools.w_treelist import treelist
# from .tools.w_ansibles import MyRunner
from pathlib import Path
from threading import Thread
from django.contrib.auth.decorators import login_required

import filetype
import threading
import shutil
import configparser
import os
import json
import yaml
import traceback
# Create your views here.
#自动化运维

config_file = r'conf\config.ini'
config = configparser.ConfigParser()
config.read(config_file, encoding='utf-8')

@login_required(login_url='/login')
def yamleditor(request):
    return render(request, 'automation/yaml-editor.html')

@csrf_exempt
@login_required(login_url='/login')
def ansible_rules(request):
    rules_file = config.get('yamlconfig','rulefile')
    get_tree = treelist()
    tree_data = get_tree.getList(rules_file,0, 1, 0, [])
    tree_data.append({'id': 199, 'pId': 0, 'name': 'site.yml', 'status': 1})
    print(tree_data)
    return HttpResponse(json.dumps({'treedata': tree_data}))


@csrf_exempt
@login_required(login_url='/login')
def upload(request):
    if request.method == "POST":
        r_data = request.FILES.get('file')
        r_data_file = request.POST.get('dir_file')
        u_ansible_file = config.get('yamlconfig', 'ansiblefile')
        u_upload_file = os.path.join(u_ansible_file, r_data_file)
        # print(request.FILES,1)
        # print(request.POST,2)
        if len(r_data_file) == 0:
            r_status = 1
            r_filename = ""
        else:
            baseDir = u_upload_file
            r_dir_filename = os.path.join(baseDir, r_data.name)
            fobj = open(r_dir_filename, 'wb')
            for chrunk in r_data.chunks():
                fobj.write(chrunk)
            fobj.close()
            r_status = 0
            r_filename = r_data.name
        return HttpResponse(json.dumps({"status":r_status, "filename":r_filename}))

@csrf_exempt
@login_required(login_url='/login')
def rulesmodify(request):
    if request.is_ajax():
        if request.method == "POST":
            rm_status = {"status":1}
            try:
                rm_type = request.POST.get('type')
                rm_old_file = request.POST.get('old_file')
                rm_new = request.POST.get('new_file')
                ansible_file = config.get('yamlconfig', 'ansiblefile')
                rm_ansible_file = os.path.join(ansible_file, rm_old_file)
                print('操作类型：%s, 修改目录或文件：%s, 其他参数：%s' % (rm_type, rm_old_file, rm_new))
                if rm_type == "move":
                    rm_new_ansible_file = os.path.join(ansible_file, rm_new)
                    os.rename(rm_ansible_file, rm_new_ansible_file)
                    rm_status["status"] = 0
                elif rm_type == "del":
                    if os.path.exists(rm_ansible_file):
                        if os.path.isdir(rm_ansible_file):
                            shutil.rmtree(rm_ansible_file)
                            print('%s 目录删除成功' % rm_ansible_file)
                        elif os.path.isfile(rm_ansible_file):
                            os.remove(rm_ansible_file)
                            print('%s 文件删除成功' % rm_ansible_file)
                        rm_status["status"] = 0
                    else:
                        print('文件不存在：%s' % rm_ansible_file)
                        rm_status["status"] = 2
                elif rm_type == "add":
                    rm_rule_other_file = ['defaults', 'handlers', 'meta', 'tasks', 'vars', 'files', 'templates']
                    if os.path.exists(rm_old_file):
                        rm_status["status"] = 2
                    else:
                        rm_other = rm_new.split('|')
                        if int(rm_other[2]) == 0:
                            if len(rm_old_file.split('\\')) == 2:
                                os.mkdir(rm_ansible_file)
                                for rm_i in range(len(rm_rule_other_file)):
                                    rm_mkdir = os.path.join(rm_ansible_file, rm_rule_other_file[rm_i])
                                    if rm_i < 5:
                                        rm_touch = os.path.join(rm_mkdir, 'main.yml')
                                        os.mkdir(rm_mkdir)
                                        Path(rm_touch).touch()
                                    else:
                                        os.mkdir(rm_mkdir)
                            else:
                                os.mkdir(rm_ansible_file)
                            rm_status["status"] = 0
                        else:
                            Path(rm_ansible_file).touch()
                            rm_status["status"] = 0
            except BaseException as b:  # 所有异常的基类
                print('deployment_zip str(e):\t\t', str(b))  # 简单
                print('deployment_zip traceback.print_exc(): %s' % traceback.print_exc())  # 最详细
                rm_status["status"] = 1
            finally:
                return HttpResponse(json.dumps(rm_status))

@csrf_exempt
@login_required(login_url='/login')
def rulescontentck(request):
    if request.is_ajax():
        if request.method == "POST":
            rcc_check_file = request.POST.get('checkfile')
            ansible_file = config.get('yamlconfig', 'ansiblefile')
            rcc_ansible_file = os.path.join(ansible_file,rcc_check_file)
            rcc_read_data = ''
            if os.path.exists(rcc_ansible_file):
                rcc_kind = filetype.guess(rcc_ansible_file)
                if rcc_kind is None:
                    try:
                        rcc_f = open(rcc_ansible_file, "r")
                        rcc_read_data = rcc_f.read()
                        rcc_f.close()
                    except:
                        print("读取异常！！！")
                        rcc_read_data = 'error'
            else:
                print("%s 文件不存在！！！" % rcc_ansible_file)
                rcc_read_data = 'error'
            print(rcc_read_data)
            return HttpResponse(rcc_read_data)

@csrf_exempt
@login_required(login_url='/login')
def rulescontentmod(request):
    if request.is_ajax():
        if request.method == "POST":
            rcm_status = {"status":1}
            try:
                rcm_data = request.POST.get("data")
                rcm_mod_file = request.POST.get("file")
                ansible_file = config.get('yamlconfig', 'ansiblefile')
                rcm_ansible_file = os.path.join(ansible_file, rcm_mod_file)
                rcm_time = datetime.now().strftime("%Y%m%d%H%M")
                rcm_back_name = rcm_ansible_file + "." + rcm_time
                shutil.move(rcm_ansible_file, rcm_back_name)
                with open(rcm_ansible_file, 'w', encoding='utf-8') as rcm_f:
                    rcm_f.write(rcm_data)
                rcm_f.close()
                rcm_status["status"] = 0
            except:
                rcm_status["status"] = 1
            finally:
                return HttpResponse(json.dumps(rcm_status))

@csrf_exempt
@login_required(login_url='/login')
def yamlwrite(request):
    if request.is_ajax():
        if request.method == 'POST':
            r_data = {"status": 1}
            try:
                yamldata = eval(request.POST.get('data'))
                yw_yaml_file = config.get('yamlconfig','yamlfile')
                yw_file_name = yamldata["title"]
                yw_file_data = yamldata["yaml"]
                yw_yaml_d = os.path.join(yw_yaml_file, yw_file_name)
                with open(yw_yaml_d, 'w', encoding='utf-8') as yw_f:
                    yw_f.write(yw_file_data)
                yw_f.close()
                yw_e = open(yw_yaml_d, encoding='utf-8')
                yw_yaml_json = json.dumps(yaml.load(yw_e))
                yw_e.close()
                y_yamllist.objects.create(yaml_name=yw_file_name, yaml_describe=yamldata["describe"], yaml_directory=yw_yaml_d, yaml_json=yw_yaml_json, is_delete=0)
                r_data["status"] = 0
            except BaseException as b:
                _log_err = "yamlwrite函数异常 --》" + str(b)
                print(_log_err)
            finally:
                return HttpResponse(json.dumps(r_data))

def selectyaml():
    sy_data = y_yamllist.objects.filter(is_delete=0).values_list('y_id', 'yaml_name', 'yaml_describe', 'yaml_json', 'is_using')
    sy_return_list = []
    sy_json_name = ['yaml_id', 'yaml_name', 'yaml_describe', 'yaml_json', 'yaml_using']
    for sy_i in sy_data:
        sy_return_json = {}
        for sy_n in range(len(sy_json_name)):
            sy_return_json[sy_json_name[sy_n]] = sy_i[sy_n]
        sy_return_list.append(sy_return_json)
    return sy_return_list


@csrf_exempt
@login_required(login_url='/login')
def yamlread(request):
    if request.is_ajax():
        if request.method == 'POST':
            yr_return_list = selectyaml()
            return HttpResponse(json.dumps({"yaml_all_list": yr_return_list }))

# @csrf_exempt
# def yamldel(request):
#     if request.is_ajax():
#         if request.method == 'POST':
#             yd_id = request.POST.get("yamlid")
#             y_yamllist.objects.filter(y_id=yd_id).update(is_delete=1)
#             yd_return_list = selectyaml()
#             return HttpResponse(json.dumps({"yaml_all_list": yd_return_list }))


def selectkeys():
    sk_data = y_yamlkeys.objects.filter(is_delete=0).values_list("k_id", "key_name", "public_key", "key_describ", "is_using")
    sk_return_list = []
    sk_json_name = ['key_id', 'key_name', 'key_public', 'key_describe', 'key_using']
    for sk_i in sk_data:
        sk_return_json = {}
        for sk_n in range(len(sk_json_name)):
            sk_return_json[sk_json_name[sk_n]] = sk_i[sk_n]
        sk_return_list.append(sk_return_json)
    return sk_return_list

@login_required(login_url='/login')
def yamlkeys(request):
    yk_keys_list = selectkeys()
    return render(request, 'automation/yaml-keys.html', {'keys_list': yk_keys_list})

@csrf_exempt
@login_required(login_url='/login')
def yamladdkey(request):
    if request.is_ajax():
        ya_status = {}
        try:
            if request.method == 'POST':
                ya_data = eval(request.POST.get("data"))
                print(ya_data)
                if len(y_yamlkeys.objects.filter(key_name=ya_data["keyname"])) == 0:
                    ya_key_file = config.get('yamlconfig','keyfile')
                    ya_key_de = os.path.join(ya_key_file, ya_data["keyname"])
                    with open(ya_key_de, 'w', encoding="utf-8") as ya_e:
                        ya_e.write(ya_data["privatekey"])
                    ya_e.close()
                    # ya_pwd = make_password(ya_data["keypwd"])
                    y_yamlkeys.objects.create(key_name=ya_data["keyname"], public_key=ya_data["publickey"], private_key_file=ya_key_de, private_pwd=ya_data["keypwd"],key_describ=ya_data["keyms"])
                    ya_status["status"] = 0
                    ya_status["keys_list"] = selectkeys()
                else:
                    ya_status["status"] = "名称重复！"
        except BaseException as b:
            ya_status["status"] = 1
            _log_err = "yamladdkey函数报错 --》" + str(b)
            print(_log_err)
        finally:
            return HttpResponse(json.dumps(ya_status))

def selecthosts():
    sh_data = y_yamlhosts.objects.filter(is_delete=0).values_list("h_id", "host_ip", "host_describ", "host_user", "host_port")
    sh_return_list = []
    sh_json_name = ['host_id', 'host_ip', 'host_describ', "host_user", "host_port"]
    for sh_i in sh_data:
        sh_return_json = {}
        for sh_n in range(len(sh_json_name)):
            sh_return_json[sh_json_name[sh_n]] = sh_i[sh_n]
        sh_return_list.append(sh_return_json)
    return sh_return_list

@login_required(login_url='/login')
def yamlhosts(request):
    yh_hosts_list = selecthosts()
    yh_keys_list = y_yamlkeys.objects.filter(is_delete=0,is_using=0).values_list('key_name')
    yh_key_list1 = []
    for yh_i in yh_keys_list:
        yh_key_list1.append(yh_i[0])
    yh_group_list = selectgroup()
    print(yh_group_list)
    return render(request, 'automation/yaml-hosts.html', {"hosts_list": yh_hosts_list, "keys_list":yh_key_list1, "group_list":yh_group_list})

@csrf_exempt
@login_required(login_url='/login')
def yamladdhost(request):
    if request.is_ajax():
        if request.method == "POST":
            yah_data = eval(request.POST.get("data"))
            if len(y_yamlhosts.objects.filter(host_ip=yah_data["hostip"])) == 0:
                y_yamlhosts.objects.create(host_ip=yah_data["hostip"], host_describ=yah_data["hostdescrib"],host_user=yah_data["hostuser"],host_port=yah_data["hostport"])
                yah_status = 0
            else:
                yah_status = 1
            yah_hosts_list = selecthosts()
            return HttpResponse(json.dumps({"host_list": yah_hosts_list, "status": yah_status}))

def selectgroup():
    sg_data = y_yamlgroup.objects.filter(is_delete=0).values_list("g_id","group_name", "group_describ", "is_using")
    sg_return_list = []
    sg_json_name = ['group_id', 'group_name', 'group_describ','group_using', 'group_key', 'group_host']
    for sg_i in sg_data:
        sg_return_json = {}
        sg_id = y_yamlgroup.objects.get(g_id=sg_i[0])
        sg_hosts = sg_id.associated_host.filter(is_delete=0, is_using=0).values("host_ip")
        sg_key = sg_id.associated_key.filter(is_delete=0, is_using=0).values_list("key_name")[0][0]
        for sg_n in range(len(sg_json_name)):
            if sg_n == 4:
                sg_return_json[sg_json_name[sg_n]] = sg_key
            elif sg_n == 5:
                sg_return_json[sg_json_name[sg_n]] = list(sg_hosts)
            else:
                sg_return_json[sg_json_name[sg_n]] = sg_i[sg_n]
        sg_return_list.append(sg_return_json)
    return sg_return_list

def group_rel(group_id):
    gr_ce_json = {}
    gr_ce_host_json = {}
    gr_host_list = []
    print("添加规则组ID：%s" % group_id)
    gr_id = y_yamlgroup.objects.get(g_id=group_id)
    gr_data = y_yamlgroup.objects.filter(g_id=group_id).values_list("g_id", "group_name")[0]
    gr_hosts = gr_id.associated_host.filter(is_delete=0, is_using=0).values_list("host_ip", "host_user", "host_port")
    gr_key = gr_id.associated_key.filter(is_delete=0, is_using=0).values_list("key_name", "private_key_file", "private_pwd")[0]
    in_status = len(r_group_rules.objects.filter(g_id=group_id))
    if gr_key[0] == "local":
        for gr_i in gr_hosts:
            gr_host_json = {}
            gr_host_json["hostname"] = gr_i[0]
            gr_host_list.append(gr_host_json)
        gr_ce_host_json["hosts"] = gr_host_list
        gr_ce_json[gr_data[1]] = gr_ce_host_json
        if in_status == 0:
            r_group_rules.objects.create(g_id=group_id, group_rules=gr_ce_json)
            print("规则添加成功：%s" % gr_ce_json)
        else:
            r_group_rules.objects.filter(g_id=group_id).update(group_rules=gr_ce_json, modifyTime=datetime.now())
            print("规则修改成功：%s" % gr_ce_json)
    else:
        for gr_i in gr_hosts:
            gr_host_json = {}
            gr_host_json["username"] = gr_i[1]
            gr_host_json["hostname"] = gr_i[0]
            gr_host_json["ip"] = gr_i[0]
            gr_host_json["ssh_key"] = gr_key[1]
            gr_host_json["password"] = gr_key[2]
            gr_host_json["port"] = gr_i[2]
            gr_host_list.append(gr_host_json)
        gr_ce_host_json["hosts"] = gr_host_list
        gr_ce_json[gr_data[1]] = gr_ce_host_json
        if in_status == 0:
            r_group_rules.objects.create(g_id=group_id, group_rules=gr_ce_json)
            print("规则添加成功：%s" % gr_ce_json)
        else:
            r_group_rules.objects.filter(g_id=group_id).update(group_rules=gr_ce_json, modifyTime=datetime.now())
            print("规则修改成功：%s" % gr_ce_json)
    return gr_ce_json

@csrf_exempt
@login_required(login_url='/login')
def yamladdgroup(request):
    if request.is_ajax():
        if request.method == "POST":
            try:
                yag_data = eval(request.POST.get("data"))
                if len(y_yamlgroup.objects.filter(group_name=yag_data["groupname"])) == 0:
                    yyg = y_yamlgroup(group_name=yag_data["groupname"], group_describ=yag_data["groupdescribe"])
                    yyg.save()
                    yag_keydata = y_yamlkeys.objects.get(key_name=yag_data["keyslist"]).k_id
                    yyg.associated_key.add(yag_keydata)
                    print(yag_data["groupip"])
                    yag_list = yag_data["groupip"].split(',')
                    print(yag_list)
                    for yag_i in yag_list:
                        yyh = y_yamlhosts.objects.get(host_ip=yag_i).h_id
                        yyg.associated_host.add(yyh)
                    yyg.save()
                    yag_status = 0
                else:
                    yag_status = 1
                yag_group_id = y_yamlgroup.objects.filter(group_name=yag_data["groupname"]).values_list("g_id")[0][0]
                group_rel(yag_group_id)
                yag_group_list = selectgroup()
                return HttpResponse(json.dumps({"group_list": yag_group_list, "status": yag_status}))
            except BaseException as b:  # 所有异常的基类
                print('deployment_zip str(e):\t\t', str(b))  # 简单
                print('deployment_zip traceback.print_exc(): %s' % traceback.print_exc())  # 最详细
                yag_status = 2
                yag_group_list = selectgroup()
                return HttpResponse(json.dumps({"group_list": yag_group_list, "status": yag_status}))

@csrf_exempt
@login_required(login_url='/login')
def yamlmodgroup(request):
    if request.is_ajax():
        if request.method == "POST":
            try:
                ymg_data = eval(request.POST.get("data"))
                ymg_id = ymg_data.pop("group_id")
                ymg_yyg = y_yamlgroup.objects.get(g_id=ymg_id)
                print("修改ID：%s，修改内容：%s" % (ymg_id, ymg_data))
                for ymg_k, ymg_v in ymg_data.items():
                    if ymg_k == "group_host":
                        ymg_new_ip = ymg_v.split(',')
                        ymg_old_ip = ymg_yyg.associated_host.filter(is_delete=0, is_using=0).values_list("host_ip")
                        ymg_old_ip_list = [x[0] for x in ymg_old_ip]
                        if len(ymg_new_ip) > len(ymg_old_ip_list):
                            poor_list = [x for x in ymg_new_ip if x not in ymg_old_ip_list]
                            for ymg_i in poor_list:
                                ymg_yyh = y_yamlhosts.objects.get(host_ip=ymg_i).h_id
                                ymg_yyg.associated_host.add(ymg_yyh)
                                ymg_yyg.save()
                        else:
                            poor_list = [x for x in ymg_old_ip_list if x not in ymg_new_ip]
                            for ymg_i in poor_list:
                                ymg_yyh = y_yamlhosts.objects.get(host_ip=ymg_i).h_id
                                ymg_yyg.associated_host.remove(ymg_yyh)
                                ymg_yyg.save()
                    elif ymg_k == "group_key":
                        ymg_key = ymg_yyg.associated_key.filter(is_delete=0, is_using=0).values_list("k_id")[0][0]
                        ymg_yyg.associated_key.remove(ymg_key)
                        ymg_key_id = y_yamlkeys.objects.get(key_name=ymg_v).k_id
                        ymg_yyg.associated_key.add(ymg_key_id)
                    else:
                        k_v_dict = {ymg_k:ymg_v, "modifyTime":datetime.now()}
                        y_yamlgroup.objects.filter(g_id=ymg_id).update(**k_v_dict)
                ymg_status = 0
                group_rel(ymg_id)
                ymg_group_list = selectgroup()
                return HttpResponse(json.dumps({"group_list": ymg_group_list, "status": ymg_status}))
            except BaseException as b:  # 所有异常的基类
                print('deployment_zip str(e):\t\t', str(b))  # 简单
                print('deployment_zip traceback.print_exc(): %s' % traceback.print_exc())  # 最详细
                ymg_status = 1
                ymg_group_list = selectgroup()
                return HttpResponse(json.dumps({"group_list": ymg_group_list, "status": ymg_status}))

# def group_rel(group_data):
#     gr_ce_json = {}
#     gr_host_list = []
#     gr_new_ip = group_data["groupip"][:-1].split(',')
#     gr_key_status = y_yamlkeys.objects.filter(key_name=group_data["keyslist"]).values_list("private_key_file","private_pwd")[0]
#     if group_data["keyslist"] == "local":
#         for gr_i in gr_new_ip:
#             gr_host_json = {}
#             gr_host_json["hostname"] = gr_i
#             gr_host_list.append(gr_host_json)
#         gr_ce_json[group_data["groupname"]] = gr_host_list
#         print(gr_ce_json)
#     else:
#         for gr_i in gr_new_ip:
#             gr_host_json = {}
#             gr_host_status = y_yamlhosts.objects.filter(host_ip=gr_i).values_list('host_user','host_port')[0]
#             gr_host_json["username"] = gr_host_status[0]
#             gr_host_json["hostname"] = gr_i
#             gr_host_json["ip"] = gr_i
#             gr_host_json["ssh_key"] = gr_key_status[0]
#             gr_host_json["password"] = gr_key_status[1]
#             gr_host_json["port"] = gr_host_status[1]
#             gr_host_list.append(gr_host_json)
#         gr_ce_json[group_data["groupname"]] = gr_host_list
#         print(gr_ce_json)
#     return gr_ce_json




@csrf_exempt
@login_required(login_url='/login')
def alldel(request):
    ad_list = {}
    if request.is_ajax():
        if request.method == "POST":
            try:
                ad_id = request.POST.get("id")
                ad_type = request.POST.get("type")
                if ad_type == "host":
                    y_yamlhosts.objects.filter(h_id=ad_id).update(is_delete=1, modifyTime=datetime.now())
                    ad_list["data_list"] = selecthosts()
                    ad_list["status"] = 0
                elif ad_type == "key":
                    k_sql = "select ygk.id from y_yamlkeys as yk LEFT JOIN y_yamlgroup_associated_key as ygk on yk.k_id = ygk.y_yamlkeys_id where yk.k_id=2"
                    cursor = connection.cursor()
                    cursor.execute(k_sql)
                    k_g_data = cursor.fetchall()
                    if k_g_data[0][0] != None:
                        ad_list["status"] = 2
                    else:
                        y_yamlkeys.objects.filter(k_id=ad_id).update(is_delete=1, modifyTime=datetime.now())
                        key_file = y_yamlkeys.objects.filter(k_id=ad_id).values_list("private_key_file")[0][0]
                        os.remove(key_file)
                        ad_list["data_list"] = selectkeys()
                        ad_list["status"] = 0
                elif ad_type == "yaml":
                    y_yamllist.objects.filter(y_id=ad_id).update(is_delete=1, modifyTime=datetime.now())
                    ad_list["data_list"] = selectyaml()
                    ad_list["status"] = 0
                elif ad_type == "group":
                    y_yamlgroup.objects.filter(g_id=ad_id).update(is_delete=1, modifyTime=datetime.now())
                    ad_list["data_list"] = selectgroup()
                    ad_list["status"] = 0
            except BaseException as b:
                _log_err = "alldel函数异常 --》" + str(b)
                ad_list["status"] = 1
                print(_log_err)
            finally:
                return HttpResponse(json.dumps(ad_list))

@csrf_exempt
@login_required(login_url='/login')
def alldis(request):
    ads_json = {}
    if request.is_ajax():
        if request.method == "POST":
            try:
                ads_id = request.POST.get("id")
                ads_status = request.POST.get("status")
                ads_type = request.POST.get("type")
                print("修改分类：%s, 修改ID：%s, 修改状态：%s" % (ads_type, ads_id, ads_status))
                if ads_type == "group":
                    y_yamlgroup.objects.filter(g_id=ads_id).update(is_using=ads_status, modifyTime=datetime.now())
                    ads_json["status"] = 0
                elif ads_type == "key":

                    k_sql = "select ygk.id from y_yamlkeys as yk LEFT JOIN y_yamlgroup_associated_key as ygk on yk.k_id = ygk.y_yamlkeys_id where yk.k_id=2"
                    cursor = connection.cursor()
                    cursor.execute(k_sql)
                    k_g_data = cursor.fetchall()
                    print(k_g_data)
                    if k_g_data[0][0] != None:
                        ads_json["status"] = 2
                    else:
                        y_yamlkeys.objects.filter(k_id=ads_id).update(is_using=ads_status, modifyTime=datetime.now())
                        ads_json["status"] = 0
            except BaseException as b:
                _log_err = "alldis函数异常 --》" + str(b)
                ads_json["status"] = 1
            finally:
                return HttpResponse(json.dumps(ads_json))

@login_required(login_url='/login')
def yamlperform(request):
    yp_group_data = selectgroup()
    yp_yaml_data = selectyaml()
    yp_yaml_list = []
    yp_group_list = []
    for yp_i in yp_yaml_data:
        if yp_i["yaml_using"] == 0:
            yp_yaml_json = {}
            yp_yaml_json["yaml_id"] = yp_i["yaml_id"]
            yp_yaml_json["yaml_name"] = yp_i["yaml_name"]
            yp_yaml_list.append(yp_yaml_json)
    for yp_n in yp_group_data:
        if yp_n["group_using"] == 0:
            yp_group_json = {}
            yp_group_host_list = []
            yp_group_json["group_id"] = yp_n["group_id"]
            yp_group_json["group_name"] = yp_n["group_name"]
            yp_group_json["group_key"] = yp_n["group_key"]
            [yp_group_host_list.append(yp_x["host_ip"]) for yp_x in yp_n["group_host"]]
            yp_group_json["group_host"] = yp_group_host_list
            yp_group_list.append(yp_group_json)
    print(yp_yaml_list)
    print(yp_group_list)
    return render(request, 'automation/yaml-perform.html', {"group_list":yp_group_list, "yaml_list":yp_yaml_list})


@csrf_exempt
@login_required(login_url='/login')
def startperform(request):
    if request.is_ajax():
        if request.method == "POST":
            return_data = {}
            username = str(request.user)
            try:
                sp_data = eval(request.POST.get("data"))
                sp_type = request.POST.get("type")
                r_data = []
                sp_rel = eval(r_group_rules.objects.filter(g_id=sp_data["group_id"]).values_list("group_rules")[0][0])
                sp_rel_name = sp_data["group_name"]
                # rapi = MyRunner(sp_rel)
                if sp_type == "shell":
                    sp_cmd = sp_data["cmd"]
                    sp_type = "shell"
                    # rapi.run(sp_rel_name, sp_type, sp_cmd)
                    # r_data,dict_data = rapi.get_result()
                    # if dict_data["success"] != {}:
                    #     group_txt = ",".join(sp_data["group_host"])
                    #     inc_data = {'h_type': 1, 'exe_user':username, 'exe_group':group_txt, 'exe_shell':sp_cmd, 'exe_results':dict_data}
                    #     y_history.objects.create(**inc_data)

                elif sp_type == "playbook":
                    sp_yaml_file = y_yamllist.objects.filter(y_id=sp_data["yaml_id"]).values_list("yaml_directory")[0][0]
                    # rapi.run_playbook(sp_rel_name, sp_yaml_file, eval(sp_data["playval"]))
                    # r_data,dict_data = rapi.get_result()
                    # if dict_data["success"] != {}:
                    #     group_txt = ",".join(sp_data["group_host"])
                    #     inc_data = {'h_type':2, 'exe_user':username, 'exe_group':group_txt, 'exe_playbook':sp_yaml_file, 'exe_value':eval(sp_data["playval"]), 'exe_results':dict_data}
                    #     y_history.objects.create(**inc_data)
                elif sp_type == "rule":
                    sp_tag = [sp_data["tag"]]
                    sp_val = eval(sp_data["val"])
                    # rapi.run_rule(sp_rel_name, sp_data["file"],sp_tag,sp_val)
                    # r_data,dict_data = rapi.get_result()
                    # if dict_data["success"] != {}:
                    #     group_txt = ",".join(sp_data["group_host"])
                    #     inc_data = {'h_type':3, 'exe_user':username, 'exe_group':group_txt, 'exe_rule':sp_tag, 'exe_value':sp_val, 'exe_rule_file':sp_data["file"], 'exe_results':dict_data}
                    #     y_history.objects.create(**inc_data)
                return_data["status"] = 0
                return_data["r_data"] = r_data
            except BaseException as b:
                _log_err = "startperform函数异常 --》" + str(b)
                print(_log_err)
                return_data["status"] = 1
            finally:
                return HttpResponse(json.dumps(return_data))

@csrf_exempt
@login_required(login_url='/login')
def yamlhistory(request):
    if request.is_ajax():
        if request.method == "POST":
            r_data  = {}
            try:
                htype = int(request.POST.get("type"))
                cursor = connection.cursor()
                h_r_data = []
                if htype == 1:
                    h_sql = """select exe_user, exe_group, exe_shell, exe_results, createDate from y_history where h_type = 1"""
                    cursor.execute(h_sql)
                    h_data = cursor.fetchall()
                    h_aduit_name = [desc[0] for desc in cursor.description]
                    h_r_data = deal_hdata(h_data, h_aduit_name)
                elif htype == 2:
                    h_sql = """select exe_user, exe_group,exe_playbook, exe_value, exe_results, createDate from y_history where h_type = 2"""
                    cursor.execute(h_sql)
                    h_data = cursor.fetchall()
                    h_aduit_name = [desc[0] for desc in cursor.description]
                    h_r_data = deal_hdata(h_data, h_aduit_name)
                elif htype == 3:
                    h_sql = """select exe_user, exe_group,exe_value, exe_rule, exe_rule_file, exe_results, createDate from y_history where h_type = 3"""
                    cursor.execute(h_sql)
                    h_data = cursor.fetchall()
                    h_aduit_name = [desc[0] for desc in cursor.description]
                    h_r_data = deal_hdata(h_data, h_aduit_name)
                r_data["data"] = h_r_data
                r_data["status"] = 0
                print(r_data)
            except BaseException as b:
                _log_err = "yamlhistory函数异常 --》" + str(b)
                print(_log_err)
                r_data["status"] = 1
            finally:
                return HttpResponse(json.dumps(r_data))

def deal_hdata(data,name_list):
    data_list = []
    for row in data:
        objDict = {}
        n = 0
        # 把每一行的数据遍历出来放到Dict中
        for index, value in enumerate(row):
            if name_list[index] == "exe_results":
                objDict[name_list[index]] = json.dumps(eval(value), indent=4)
            else:
                objDict[name_list[index]] = value
        objDict["createDate"] = objDict["createDate"].strftime("%Y-%m-%d %H:%M:%S")
        data_list.append(objDict)
    return data_list